package cn.wolfcode.expection;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ControllerAdviceForException {


    @ExceptionHandler(RuntimeException.class)

    public Object handlerException(Model model, RuntimeException e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace();

        //如果用户访问的处理方法本来是返回视图的现在也应该返回视图
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset=utf-8");

            JsonResult json = new JsonResult(false, "操作失败，请联系管理员");
            try {
                response.getWriter().println(JSON.toJSONString(json));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            return null;
        } else {
            model.addAttribute("ex", e);
            return "/common/error.ftl";//返回错误视图
        }
    }
}
